// src/composables/useGunForm.js

import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

export function useGunForm() {
    const gunDialogVisible = ref(false);
    const gunForm = reactive({
        id: '',
        gunCode: '',
        gunType: '',
        gunName: '',
        outputPower: 0,
        remark: '',
        pileId: '', // 必须关联到一个充电桩
    });
    const isAddingGun = ref(true);

    // 打开弹窗
    const openGunDialog = (gun = null) => {
        if (gun) {
            Object.assign(gunForm, gun);
            isAddingGun.value = false;
        } else {
            Object.assign(gunForm, {
                id: '',
                gunCode: '',
                gunType: '',
                gunName: '',
                outputPower: 0,
                remark: '',
                pileId: '',
            });
            isAddingGun.value = true;
        }
        gunDialogVisible.value = true;
    };

    // 保存充电枪
// 保存充电枪
    const saveGun = (chargingGuns) => {

        // 确保 chargingGuns 是一个数组
        if (!Array.isArray(chargingGuns)) {
            console.error("chargingGuns 不是一个数组，实际值为：", chargingGuns);
            return ElMessage.error("操作失败：充电枪列表数据格式错误");
        }

        if (isAddingGun.value) {
            // 新增逻辑
            if (!gunForm.gunCode) {
                gunForm.gunCode = `gun_${Date.now()}`; // 生成唯一 gunCode
            }
            chargingGuns.push({ ...gunForm });
            ElMessage.success("新增充电枪成功");
        } else {
            // 编辑逻辑
            const index = chargingGuns.findIndex((g) => g.gunCode === gunForm.gunCode);
            if (index !== -1) {
                chargingGuns.splice(index, 1, { ...gunForm });
                ElMessage.success("编辑充电枪成功");
            } else {
                ElMessage.error("编辑失败：未找到本地的充电枪");
                console.error("保存失败 - 当前 gunForm：", gunForm);
                console.error("保存失败 - 本地 chargingGuns：", chargingGuns);
            }
        }

        // 触发响应式更新
        chargingGuns.splice(0, chargingGuns.length, ...chargingGuns);

        // 关闭弹窗
        gunDialogVisible.value = false;
    };



    // 删除充电枪
    const removeGun = (chargingGuns, index) => {
        chargingGuns.splice(index, 1);
        ElMessage.success("删除充电枪成功");
    };

    return {
        gunDialogVisible,
        gunForm,
        isAddingGun,
        openGunDialog,
        saveGun,
        removeGun,
    };
}
